import { CategoryCascader } from '@/components/CategoryCascader';
import FilePaths from '@/components/resourceLibraryComp/FilePaths';
import { RefFn } from '@/components/resourceLibraryComp/FilePaths/interface';
import { TradeSelect } from '@/components/TradeSelect';
import { useAppSelector } from '@/redux/store';
import { useAntdTable } from 'ahooks';
import type { TableProps } from 'antd';
import { Button, Form, Input, Select, Table } from 'antd';
import { useMemo, useRef, useState } from 'react';
import Source from '../Entity/Source';
import { useYmTableScrollY } from '../hooks/useTableScorll';
import { MainSearchTableProps } from './interface';

/**
 * @desc 课件类型选择
 */
const courseTypeOptions = [
  {
    label: '视频课件',
    value: '700',
  },
  {
    label: '图文课件',
    value: '800',
  },
  {
    label: 'pdf课件',
    value: '900',
  },
];

export function MainSearchTable({
  getColumns,
  getRowSelection,
  searchFields,
  tableRequest,
  value,
  valueSet,
}: MainSearchTableProps) {
  // 文件路径相关内容
  const filePathRef = useRef<RefFn>(null);
  const [currentFolder, setCurrentFolder] = useState<string>('0');
  // 获取初始化配置用的上下文参数

  const [form] = Form.useForm();

  // 初始化列表字段获取
  const [columns] = useState(() => {
    return getColumns?.();
  });

  const { entId } = useAppSelector((state) => state.loginEnt);
  const { tableProps, search } = useAntdTable(
    async ({ pageSize = 10, current = 1, sorter = {} }, fromParams) => {
      const dateSort = sorter.order?.replace('end', '');
      const parentId = currentFolder;
      return (
        (await tableRequest?.(current, pageSize, {
          entId,
          dateSort,
          parentId,
          ...fromParams,
        })) ?? { total: 0, list: [] }
      );
    },
    { form, manual: false, refreshDeps: [currentFolder] },
  );

  if (tableProps.pagination) {
    Object.assign(tableProps.pagination, {
      showTotal: (n: number) => <>共{n}条</>,
      pageSizeOptions: [10, 15, 20, 30, 40, 50],
      showSizeChanger: true,
      // pageSize: 15,
    });
  }

  const { tableRef, scrollY, className } = useYmTableScrollY();
  const [props] = CategoryCascader.useFieldLevelTwo();

  // 查询表单配置内容
  const formItemReactNode = useMemo(() => {
    const FormName = (
      <Form.Item name="resourceName" label="名称" key="resourceName">
        <Input placeholder="名称"></Input>
      </Form.Item>
    );
    const FormCourse = (
      <Form.Item name="coursewareGroup" label="类型" initialValue="700" key="coursewareGroup">
        <Select options={courseTypeOptions}></Select>
      </Form.Item>
    );

    const FormTrade = (
      <Form.Item name="trade" label="行业" key="trade">
        <TradeSelect />
      </Form.Item>
    );

    const FormClass = (
      <Form.Item name="classId" label="分类" {...props} key="classId">
        <CategoryCascader placeholder="全部" />
      </Form.Item>
    );

    return (
      <>
        {searchFields?.map((v) => {
          if (v === 'name') {
            return FormName;
          } else if (v === 'classId') {
            return FormClass;
          } else if (v === 'coursewareGroup') {
            return FormCourse;
          } else if (v === 'trade') {
            return FormTrade;
          } else {
            return null;
          }
        })}
      </>
    );
  }, [props, searchFields]);

  // 选择配置
  const rowSelection = useMemo<TableProps<Source>['rowSelection']>(() => {
    const result: TableProps<Source>['rowSelection'] = {
      preserveSelectedRowKeys: true,
      fixed: 'left',
      getCheckboxProps(record) {
        return {
          disabled: record.isFolder,
          style: { display: record.isFolder ? 'none' : undefined },
        };
      },
      ...getRowSelection?.(value, valueSet, tableProps.dataSource),
    };
    return result;
  }, [getRowSelection, value, valueSet, tableProps.dataSource]);

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        height: '100%',
        width: '100%',
        padding: 16,
        paddingBottom: 0,
        boxSizing: 'border-box',
        rowGap: 16,
      }}
    >
      <Form
        layout="inline"
        form={form}
        style={{ gap: 16 }}
        labelCol={{ style: { width: 56 } }}
        wrapperCol={{ style: { width: 168 } }}
      >
        {formItemReactNode}
        <Form.Item>
          <Button htmlType="submit" style={{ borderRadius: 30 }} onClick={search.submit}>
            搜索
          </Button>
        </Form.Item>
      </Form>
      <div hidden={currentFolder === '0'}>
        <FilePaths
          ref={filePathRef}
          onBreadCrumbClick={(e, key) => {
            setCurrentFolder(key);
          }}
        />
      </div>
      <Table
        className={className()}
        ref={tableRef}
        tableLayout="fixed"
        style={{ boxSizing: 'border-box', flexGrow: 1, overflow: 'hidden' }}
        columns={columns}
        onRow={(record) => {
          return {
            onClick() {
              if (record.isFolder) {
                filePathRef.current?.onAddFilePaths({
                  resourceName: record.name,
                  resourceId: record.id,
                });
                setCurrentFolder(record.id);
              }
            },
          };
        }}
        rowSelection={rowSelection}
        scroll={{ x: '100%', y: scrollY }}
        rowKey="id"
        {...tableProps}
      />
    </div>
  );
}
